CREATE OR REPLACE FUNCTION reset_document_features() RETURNS VOID AS '
DECLARE
   v_feat_key INTEGER;
   v_ticketNumber_feat_key INTEGER;
BEGIN
    DELETE FROM t_feature;
    DELETE FROM t_feature_key;

    -- insert TicketNumber global feature key
    INSERT INTO t_feature_key(fk_id, fk_string) 
        SELECT nextval(''seq_feature_key''), ''TicketNumber'';

    SELECT currval(''seq_feature_key'') INTO v_ticketNumber_feat_key;

    -- insert TicketNumber feature of each document
    INSERT INTO t_feature(ft_id, ft_entity_id
        , ft_entity_type, ft_key_id, ft_character_value
        , ft_value_type)
    SELECT nextval(''seq_feature''), d.doc_lr_id
        , 2, v_ticketNumber_feat_key, substring(d.doc_url from ''/([^/\\\\.]+)\\\\..+$'')
        , 104
    FROM t_document d
    ORDER BY 5;

    -- insert TroubleType global feature key
    INSERT INTO t_feature_key(fk_id, fk_string) 
        SELECT nextval(''seq_feature_key''), ''TroubleType'';

    SELECT currval(''seq_feature_key'') INTO v_feat_key;

    -- insert TroubleType feature of each document
        
    INSERT INTO t_feature(ft_id, ft_entity_id
        , ft_entity_type, ft_key_id, ft_character_value
        , ft_value_type)
    SELECT nextval(''seq_feature''), d.doc_lr_id
        , 2, v_feat_key,  substring(d.doc_url from ''/([A-Z]+)/[^/]+$'')
        , 104
    FROM t_document d
    ORDER BY 5;

    ---- THIS IS HOW WE USED TO DO IT (with a table imported from coned DB called TicketTroubleTypes)
    ---- (see function reset_document_features_using_local_table() ).
    --INSERT INTO t_feature(ft_id, ft_entity_id
    --    , ft_entity_type, ft_key_id, ft_character_value
    --    , ft_value_type)
    --SELECT nextval(''seq_feature''), f.ft_entity_id
    --    , 2, v_feat_key, ttt.troubleType
    --    , 104
    --FROM TicketTroubleTypes ttt, t_feature f
    --WHERE f.ft_character_value = ttt.ticketNumber AND f.ft_key_id = v_ticketNumber_feat_key;

END;
' LANGUAGE 'plpgsql';

-- SELECT reset_document_features();